package com.bwie.system.service.impl;

import com.bwie.common.pojo.res.LoginRes;
import com.bwie.common.pojo.res.MenuRes;
import com.bwie.common.utils.TokenUtils;
import com.bwie.system.mapper.MenuMapper;
import com.bwie.system.service.MenuService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class MenuServiceImpl implements MenuService {
    private final MenuMapper menuMapper;
    private final HttpServletRequest request;
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 获取权限树
     * @return
     */
    @Override
    public List<MenuRes> getMenuTreeByUserId() {
        LoginRes loginRes = TokenUtils.getUser(request, redisTemplate);
        // 根据id查询
        List<MenuRes> list = menuMapper.getMenuList(loginRes.getUserId());
        return getMenuTree(list);
    }

    private List<MenuRes> getMenuTree(List<MenuRes> list) {
        Map<Integer, List<MenuRes>> map = list.stream().collect(Collectors.groupingBy(MenuRes::getPid));
        return setChildrenTree(0, map);
    }

    private List<MenuRes> setChildrenTree(Integer pid, Map<Integer, List<MenuRes>> map) {
        List<MenuRes> list = map.get(pid);
        // 判空
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList(); // 返回空列表而不是null
        }
        for (MenuRes menuRes : list) {
            Integer menuId = menuRes.getMenuId();
            menuRes.setChildren(setChildrenTree(menuId, map));
        }
        return list;
    }
}
